// @flow
import React from 'react'
import { Form, Input, Button, message, Radio, Upload, Icon } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import Customer from 'components/CustomerPermission'
const FormItem = Form.Item
const RadioGroup = Radio.Group
import md5 from 'md5'
import styles from './UserEdit.css'
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type Props = {
  history: Object,
  form: Object
}

type State = {
  loading: boolean,
  roles: Array<Object>,
  userRoles: Array<Object>,
  taskData: Object,
  imageUrl: string,
  remoteImageUrl: string,
  customersPermission: Array<any>,
  customerGridVisible: boolean
}

class UserEdit extends React.Component {
  props: Props
  state: State
  submit: Function
  getRoles: Function
  changeFile: Function
  beforeUpload: Function
  getCustomersPermission: Function
  roleIdsChange: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      loading: false,
      roles: [],
      userRoles: [],
      taskData: {},
      imageUrl: '',
      remoteImageUrl: '',
      customersPermission: [],
      customerGridVisible: false
    }

    this.submit = this.submit.bind(this)
    this.getRoles = this.getRoles.bind(this)
    this.changeFile = this.changeFile.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.getCustomersPermission = this.getCustomersPermission.bind(this)
    this.roleIdsChange = this.roleIdsChange.bind(this)
  }

  componentWillMount () {
    this.getRoles()
    const { data } = this.props.history.location.state
    let imageUrl = data.photo
    if (imageUrl) {
      const index = imageUrl.lastIndexOf('/')
      imageUrl = imageUrl.substring(index + 1, imageUrl.length)
      this.setState({
        imageUrl: imageUrl,
        remoteImageUrl: data.photo,
        taskData: data
      })
    }
    if (data.roleId !== '1') {
      this.setState({
        customerGridVisible: true
      })
    }
    this.setState({
      taskData: data,
      customersPermission: data.customers
    })
  }

  getCustomersPermission (data) {
    // console.log('最终结果');
    // console.log(data);
    let value = Object.values(data).filter((dd) => dd['permission'].length > 0)
    this.setState({
      customersPermission: value
    })
  }

  roleIdsChange (e) {
    const value = e.target.value
    // 系统管理员权限表格不可见
    if (value !== '1') {
      this.setState({
        customerGridVisible: true
      })
    } else {
      this.setState({
        customerGridVisible: false
      })
    }
  }

  changeFile (info) {
    const response = info.file.response
    if (response && response.code === 200000) {
      this.setState({
        imageUrl: response.result.name,
        remoteImageUrl: response.result.url
      })
    }
  }

  beforeUpload (file) {
    const type = file.type.toLocaleLowerCase()
    if (type.indexOf('image/') === -1) {
      message.error('只能上传图片', 3)
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return type.indexOf('image/') > -1
  }

  getRoles () {
    universalFetch(`${__SERVICE_API__}sys/roles/simple`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          roles: json.result
        })
      })
      .catch((err) => {
        handleFetchError(err)
        console.error(err)
      })
  }

  submit () {
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      // fieldsValue['password'] = md5(fieldsValue['password'])
      this.setState({
        loading: true
      })
      const { imageUrl } = this.state
      let values = {
        ...Object.assign({}, fieldsValue, { photo: imageUrl })
      }
      values['customers'] = this.state.customersPermission // 客户权限
      const { taskData } = this.state
      universalFetch(`${__SERVICE_API__}sys/users/${taskData.id}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(values)
        })
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            loading: false
          })
          message.success('修改成功')
          this.props.history.push('/system/userSetting')
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          message.error('修改失败')
          this.setState({
            loading: false
          })
        })
    })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { history } = this.props
    const { taskData, roles, remoteImageUrl, customerGridVisible, customersPermission } = this.state
    const token = localStorage.getItem('asset_token')
    let customerGrid = customerGridVisible ? <div
      style={{ marginBottom: 40 }}>
      <Customer {...{
        customersPermission,
        getCustomersPermission: this.getCustomersPermission,
        history
      }} />
    </div> : ''
    return (
      <div className={styles['main']}>
        <Form>
          <FormItem
            {...formItemLayout}
            label='登陆名称'
            hasFeedback
          >
            {getFieldDecorator('loginName', {
              rules: [{ required: true, message: '请填写登陆名称', whitespace: true }],
              initialValue: taskData.loginName
            })(
              <Input disabled placeholder='请填写登陆名称' />
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label='昵称'
            hasFeedback
          >
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '请填写昵称', whitespace: true }],
              initialValue: taskData.name
            })(
              <Input placeholder='请填写昵称' />
              )}
          </FormItem>
          <FormItem {...formItemLayout} label='手机号' hasFeedback>
            {
              getFieldDecorator('mobile', {
                rules: [
                  { required: true, message: '请填写手机号', whitespace: true }
                ],
                initialValue: taskData.mobile
              })(
                <Input placeholder='请填写手机号' />
              )
            }
          </FormItem>

          <FormItem {...formItemLayout} label='邮箱' hasFeedback>
            {
              getFieldDecorator('email', {
                rules: [
                  { required: true, message: '请填写邮箱' }
                ],
                initialValue: taskData.email
              })(
                <Input placeholder='请填写邮箱' />
              )
            }
          </FormItem>
          <FormItem
            {...formItemLayout}
            label='用户角色'
          >
            {getFieldDecorator('roleId', {
              rules: [{ required: true, message: '请选择角色' }],
              initialValue: taskData.roleId
            })(
              <RadioGroup onChange={this.roleIdsChange}>
                {
                  roles.map((d, i) => {
                    return <Radio key={i} value={d.value}>{d.label}</Radio>
                  })
                }
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='用户类型' hasFeedback>
            {
              getFieldDecorator('userType', {
                initialValue: taskData.userType
              })(
                <Input placeholder='请填写用户类型' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='用户头像'>
            {
              getFieldDecorator('photo', { initialValue: taskData.photo })(
                <Upload
                  {...{
                    name: 'file',
                    className: styles['avatar-uploader'],
                    action: `${__SERVICE_API__}static/statics`,
                    headers:{ 'X-Auth':token },
                    onChange: this.changeFile,
                    beforeUpload: this.beforeUpload,
                    showUploadList: false
                  }}
                  >
                  {
                    remoteImageUrl
                    ? <div className={styles['image-preview']}>
                      <img src={remoteImageUrl} style={{ width: '100%' }} />
                      <div className={styles['over-avatar']}>
                        更换图片
                      </div>
                    </div>
                    : <Button style={{ width: '150px' }}>
                      <Icon type='upload' />上传图片
                    </Button>
                  }
                </Upload>
              )
            }
          </FormItem>
          {customerGrid}
          <FormItem
            {...tailFormItemLayout}
            className={styles['footbtn']}
          >
            <Button type='primary'
              className='login-form-button'
              onClick={this.submit}
              >
              提交
            </Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={() => {
                this.props.history.push('/system/userSetting')
              }}
              >
              返回
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}
export default Form.create()(UserEdit)
